//
//  QsbkMainViewController.m
//  NewProject
//
//  Created by Livespro on 2017/5/16.
//  Copyright © 2017年 FZ. All rights reserved.
//

#import "QsbkMainViewController.h"
#import "QsbkOnlyContextViewController.h"
#import "QsbkSettingViewController.h"

#define kContextRectSmall CGRectMake(-kScreenWidth * 3/8, kScreenHeight/4, kScreenWidth/2, kScreenHeight/2)
#define kSettingRectSmall CGRectMake(kScreenWidth/4, kScreenHeight/4, kScreenWidth/2, kScreenHeight/2)

static CGFloat animationTimes = 0.5f;

typedef NS_ENUM(NSInteger, QsbkMainStatus) {
    QsbkMainStatusContext = 0,
    QsbkMainStatusSetting
};

@interface QsbkMainViewController ()<UINavigationControllerDelegate>
{
    UIPanGestureRecognizer *panG;
    
    BOOL isInterractive;
    
}
@property (nonatomic, strong)  UIPercentDrivenInteractiveTransition *interactiveTransition;

@property (nonatomic, strong)  LXPopAnimations *popAnimation;

@property (nonatomic, strong)  QsbkSettingViewController *containSetting;

@property (nonatomic, strong)  QsbkOnlyContextViewController *containContext;

@property (nonatomic, assign)  QsbkModuleType currentType;

@property (nonatomic, assign)  QsbkMainStatus currentStatus;

@end

@implementation QsbkMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

-(void)staticViewsWithoutNib{
    
    [self.naviStand removeFromSuperview];
    
    [self.view addSubview:self.containSetting.view];
    [self addChildViewController:self.containSetting];
    
    [self.view addSubview:self.containContext.view];
    [self addChildViewController:self.containContext];
    
    [self addPanGestureRecognizer];
}

#pragma mark - lazyLoad
- (QsbkSettingViewController *)containSetting{
    
    if (!_containSetting) {
        
        _containSetting = [[QsbkSettingViewController alloc]init];
        _containSetting.view.frame = CGRectMake(kScreenWidth/4, kScreenHeight/4, kScreenWidth/2, kScreenHeight/2);
        
        _containSetting.view.backgroundColor = [UIColor redColor];
    }
    return _containSetting;
}

- (QsbkOnlyContextViewController *)containContext{
    
    if (!_containContext) {
        
        _containContext = [[QsbkOnlyContextViewController alloc]init];
        _containContext.view.frame = self.view.bounds;
        
        _containContext.view.backgroundColor = [UIColor greenColor];
        
        _containContext.currentType = self.currentType;
        
        __weak typeof(self) weakSelf = self;
        _containContext.backPass = ^{
            
            [weakSelf back];
        };
    }
    return _containContext;
}

- (QsbkModuleType)currentType{
    
    if (!_currentType) {
        
        _currentType = QsbkModuleTypeDay;
    }
    return _currentType;
}

- (QsbkMainStatus)currentStatus{
    
    if (!_currentStatus) {
        
        _currentStatus = QsbkMainStatusContext;
    }
    return _currentStatus;
}


/**
 添加手势
 */
- (void)addPanGestureRecognizer{
    
    panG = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    
    [self.view addGestureRecognizer:panG];
    
    self.navigationController.delegate=self;//添加返回效果
    
//    [panG requireGestureRecognizerToFail:self.navigationController.fd_fullscreenPopGestureRecognizer];//不行，更改优先级会冲突
}

/**
 *  手势过渡的过程
 */
- (void)handlePanGesture:(UIPanGestureRecognizer *)panGesture{
    
    CGFloat transitionX = [panGesture translationInView:panGesture.view].x;
    
    //显示内容 右滑返回 - 自定义右滑转场动画
    if (transitionX >= 0 && _currentStatus == QsbkMainStatusContext) {
        //手势百分比
        
        CGFloat persent = ABS(transitionX) / kScreenWidth;
        
        switch (panGesture.state) {
            case UIGestureRecognizerStateBegan:
                //手势开始的时候标记手势状态，并开始相应的事件
                isInterractive = YES;
                [self.navigationController popViewControllerAnimated:YES];
                
                break;
            case UIGestureRecognizerStateChanged:{
                //手势过程中，通过updateInteractiveTransition设置pop过程进行的百分比
                [self.interactiveTransition updateInteractiveTransition:persent];
                
                break;
            }
            case UIGestureRecognizerStateEnded:{
                //手势完成后结束标记并且判断移动距离是否过半，过则finishInteractiveTransition完成转场操作，否者取消转场操作
                
                if (persent > 0.5) {
                    [self.interactiveTransition finishInteractiveTransition];
                }else{
                    [self.interactiveTransition cancelInteractiveTransition];
                }
                
                isInterractive = NO;
                
                break;
            }
            default:
                break;
        }
        
        return;
    }
    //显示设置 左滑无效
    if (transitionX <= 0 && _currentStatus == QsbkMainStatusSetting) return;
    
    //手势百分比
    CGFloat persent = 0;
    
    persent = ABS(transitionX) / kScreenWidth;
    
    switch (panGesture.state) {
        case UIGestureRecognizerStateBegan:
            //手势开始的时候标记手势状态，并开始相应的事件
            
//            [self leaveGesture:0.0f];
            
            break;
        case UIGestureRecognizerStateChanged:{
            
            [self leaveGesture:persent];
            
            break;
        }
        case UIGestureRecognizerStateEnded:{
            
            if (persent > 0.5) {
            
                [self finishAnimation:persent Status:_currentStatus];
            }else{
                
                [self finishAnimation:persent Status:(_currentStatus == QsbkMainStatusContext) ? QsbkMainStatusSetting : QsbkMainStatusContext];
            }
            
            break;
        }
        default:
            break;
    }
}

#pragma mark - 切换显示动画 - >
- (void)leaveGesture:(CGFloat)persent{
    
    if (_currentStatus == QsbkMainStatusContext) {//显示内容
        
        _containSetting.view.layer.frame = CGRectMake((kScreenWidth - kSettingRectSmall.size.width *(1 + persent))/2, (kScreenHeight - kSettingRectSmall.size.height *(1 + persent))/2, kSettingRectSmall.size.width *(1 + persent), kSettingRectSmall.size.height *(1 + persent));
        
        _containContext.view.layer.frame = CGRectMake(kContextRectSmall.origin.x * persent, kContextRectSmall.origin.y *persent, (kScreenWidth - kContextRectSmall.size.width) *(1 - persent) + kContextRectSmall.size.width, (kScreenHeight - kContextRectSmall.size.height) *(1 - persent) + kContextRectSmall.size.height);
        
    } else {//显示设置
        
        _containSetting.view.layer.frame = CGRectMake(kSettingRectSmall.origin.x * persent, kSettingRectSmall.origin.y *persent, (kScreenWidth - kSettingRectSmall.size.width) *(1 - persent) + kSettingRectSmall.size.width, (kScreenHeight - kSettingRectSmall.size.height) *(1 - persent) + kSettingRectSmall.size.height);
        
        _containContext.view.layer.frame = CGRectMake(kContextRectSmall.origin.x *(1 - persent), (kScreenHeight - kContextRectSmall.size.height *(1 + persent))/2, (kScreenWidth - kContextRectSmall.size.width) *persent + kContextRectSmall.size.width, (kScreenHeight - kContextRectSmall.size.height) *persent + kContextRectSmall.size.height);
        
    }
    
}

- (void)finishAnimation:(CGFloat)persent Status:(QsbkMainStatus)status{

    NSTimeInterval animationTimeMust = (status == _currentStatus) ? (1-persent)*animationTimes : persent*animationTimes;
    
    if (status == QsbkMainStatusContext) {//显示内容
        
        [UIView animateWithDuration:animationTimeMust animations:^{
            
            _containSetting.view.layer.frame = self.view.bounds;
            _containContext.view.layer.frame = kContextRectSmall;
            
        } completion:^(BOOL finished) {
            
            _containSetting.view.frame = self.view.bounds;
            _containContext.view.frame = kContextRectSmall;
            
            _currentStatus = QsbkMainStatusSetting;
        }];
    } else {//显示设置
        
        [UIView animateWithDuration:animationTimeMust animations:^{
            
            _containSetting.view.layer.frame = kSettingRectSmall;
            _containContext.view.layer.frame = self.view.bounds;
            
        } completion:^(BOOL finished) {
            
            _containSetting.view.frame = kSettingRectSmall;
            _containContext.view.frame = self.view.bounds;
            
            _currentStatus = QsbkMainStatusContext;
            
        }];
    }
    
}

#pragma mark - 横幅动画
- (void)bannerAnimation{
   
    //快照
    UIView *temp=[self.containContext.naviStand snapshotViewAfterScreenUpdates:NO];

    CAShapeLayer *layer;
    
}

#pragma mark - 转场动画 - >
- (LXPopAnimations *)popAnimation{
    
    if ( !_popAnimation) {
        
        _popAnimation = [[LXPopAnimations alloc]init];
    }
    return _popAnimation;
}

- (UIPercentDrivenInteractiveTransition *)interactiveTransition{
    
    if (!_interactiveTransition) {
        
        _interactiveTransition = [[UIPercentDrivenInteractiveTransition alloc]init];
    }
    return _interactiveTransition;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self.navigationController setValue:@(NO) forKey:@"currentAnimating"];
}

#pragma mark-UINavigationControllerDelegate

- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);{
    
    return (operation == UINavigationControllerOperationPush ? nil :self.popAnimation) ;
    
}
- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                                   interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController NS_AVAILABLE_IOS(7_0);{
    
    return isInterractive ? self.interactiveTransition : nil;
}

@end


@implementation LXPopAnimations

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext;{
    
    return 0.3f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;{
    
    UIViewController *fromVC=[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    
    UIViewController *toVC=[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    NSTimeInterval duration=[self transitionDuration:transitionContext];
    
    UIView *containView = [transitionContext containerView];
    
    [containView addSubview:toVC.view];
    //隐藏fromView,用屏幕快照做动画效果
    UIView *tempView=[fromVC.view snapshotViewAfterScreenUpdates:NO];
    
    tempView.frame=containView.frame;
    
    [containView addSubview:tempView];
    
    fromVC.view.hidden = YES;
    
    // Give both VCs the same start frame
    CGRect initialFrame = [transitionContext initialFrameForViewController:fromVC];
    toVC.view.frame = initialFrame;
    
    // flip the to VC halfway round - hiding it
    toVC.view.layer.transform =CATransform3DMakeRotation(-M_PI_2, 0.0, 1.0, 0.0);
    
    [UIView animateKeyframesWithDuration:duration
                                   delay:0.0
                                 options:UIViewKeyframeAnimationOptionCalculationModeCubic
                              animations:^{
                                  [UIView addKeyframeWithRelativeStartTime:0.0
                                                          relativeDuration:0.5
                                                                animations:^{
                                                                    // rotate the from view
                                                                    tempView.layer.transform =CATransform3DMakeRotation(M_PI_2, 0.0, 1.0, 0.0);
                                                                }];
                                  
                                  [UIView addKeyframeWithRelativeStartTime:0.5
                                                          relativeDuration:0.5
                                                                animations:^{
                                                                    // rotate the to view
                                                                    toVC.view.layer.transform =CATransform3DMakeRotation(0.0, 0.0, 1.0, 0.0);
                                                                }];
                              } completion:^(BOOL finished) {
                                  fromVC.view.layer.transform = CATransform3DIdentity;
                                  toVC.view.layer.transform = CATransform3DIdentity;
                                  containView.layer.transform = CATransform3DIdentity;
                                  
                                  if ([transitionContext transitionWasCancelled]) {
                                      [transitionContext completeTransition:NO];
                                      fromVC.view.hidden = NO;
                                      [tempView removeFromSuperview];
                                  }else{
                                      [transitionContext completeTransition:YES];
                                      [tempView removeFromSuperview];
                                      
                                      [toVC.navigationController setValue:@(NO) forKey:@"currentAnimating"];
                                  }
                                  
                              }];

}

@end
